// pages/student/student.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollTop:0,
    currentPage:0,
    loadNumberLimit:0,
    inputSearchKey:'',
    list:[],
    ordersShow:false,
    studentOrders:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(event:any) {
    wx.showLoading({title:'加载中'})
    console.log(event);
    
    let _id = event._id;
    console.log(_id);
   let group = await (await wx.cloud.database().collection('groups').doc(_id).get()).data;
   let students = group.students;
   console.log(students);
   
   this.setData({
    list:students
   })
   wx.hideLoading()
  }, 
 async addSign(event:WechatMiniprogram.CustomEvent){
    //输入学生id，查询order表记录
    //如果查询不到，提示为该学生添加订单记录
    //如果查询到一个订单，那么直接添加签到记录
    //如果查询到多个订单，那么弹出选择框进行签到。点击某个订单，赋值订单id,添加订单记录
    //签到时校验是否近一个小时有某同学的签到记录，如果有记录，那么提示请勿重复签到
    //签到之后对列表进行标记，students 添加 isHasSign == true ; 循环查询标注
    let studentId = event.currentTarget.dataset._id;
    let studentName = event.currentTarget.dataset.name;
    let app = getApp();
    wx.showLoading({title:'加载中',mask:true});
    console.log(event);
    
    let studentOrders  =  await  (await wx.cloud.database().collection('orders').where({studentId:studentId}).get()).data;
    console.log(studentOrders);
    this.setData({
      studentOrders:studentOrders
    })
    if(studentOrders.length==0){
      wx.showModal({title:'提示',content:'该学生没有订单记录，是否前往添加',success(res){
        if(res.confirm){
          wx.navigateTo({url:`/pages/orderAdd/orderAdd?_id=${studentId}&name=${studentName}`})
        }
      }})
    }
    if(studentOrders.length==1){
      wx.showLoading({title:'签到中',mask:true});
      let studentOrder = studentOrders[0];
      this.sign(studentOrder);
    }
    if(studentOrders.length>1){
      console.log('超过1条签到记录');
      let orders = []
      for (let index = 0; index < studentOrders.length; index++) {
        let item = studentOrders[index];
        orders.push({
          name:item.subject,
          _id:item._id,
          index:index,
          subname:item.form + ' | ' + item.classify 
        });
      }
      console.log(orders);
      this.setData({
        ordersShow:true,
        orders:orders,
      })

    }
    wx.hideLoading();
  },

  async sign(studentOrder:any){
    let studentId = studentOrder.studentId;
    let surplus = studentOrder.surplus;
    let unitPrice =  studentOrder.unitPrice;
    let times =  studentOrder.times;
    console.log(surplus);
    
    if(surplus==''&&surplus!==0){
      surplus = Number(times);
    }else{
      surplus = Number(surplus);
    }
    if(surplus==0){
      surplus = 0
    }
    let beforeTime = surplus;
    console.log('surplus',surplus);
    
    if(surplus-1>=0){
      surplus  = surplus-1; 
    }else{
      surplus  = 0; 
      wx.showModal({title:'提示',content:'该学生课程已完成，无法签到'});
      wx.hideLoading()
      return null
    }

    console.log(surplus,beforeTime);
    
    let currentPrice = (Number(surplus)*Number(unitPrice)).toFixed(2);
    console.log('剩余费用',currentPrice);
    let currentTime = new Date().getTime();
    let oneOurBeforeTime = currentTime - 60*60*1000;
    let _ = wx.cloud.database().command;
    let signs =  await (await wx.cloud.database().collection('signs').where({studentId:studentId,_createTime:_.gt(oneOurBeforeTime)}).get()).data;
    console.log('签到记录',signs);
    if(signs.length>=1){
      wx.showModal({title:'提示',content:"该学生在最近一小时有签到记录，请勿重复签到"})
    }else{
      await wx.cloud.database().collection('signs').add({data:{
        orderId:studentOrder._id,
        classify:studentOrder.classify,
        form:studentOrder.form,
        price:studentOrder.price,
        remark:studentOrder.remark,
        studentId:studentOrder.studentId,
        studentName:studentOrder.studentName,
        subject:studentOrder.subject,
        times:studentOrder.times,
        unitPrice:studentOrder.unitPrice,
        beforeTime:beforeTime,
        currentPrice:currentPrice,
        surplus:surplus,
        _createTime:new Date().getTime(),
        userName:app.globalData.userName,
        userPhone:app.globalData.userPhone,
        userRole:app.globalData.userRole,
      }}).then(async res=>{
        await wx.cloud.database().collection('orders').doc(studentOrder._id).update({data:{
          _updateTime:new Date().getTime(),
          surplus:surplus,
          currentPrice:currentPrice,
          signs:_.addToSet(res._id)
        }});
        wx.hideLoading()
        wx.showToast({title:'签到成功'});
      })
    }

    wx.hideLoading()
  },

  async ordersSelect(event:any){
    console.log(event);
    let studentOrder = this.data.studentOrders[event.detail.index];
    console.log(studentOrder);
     await this.sign(studentOrder);
    this.setData({
      ordersShow:false
    })
  },

  ordersOpen(){
    this.setData({
      ordersShow:true
    })
  },


  ordersClose(){
    this.setData({
      ordersShow:false
    })
  },


  inputSearchKey(event: any) {
    this.setData({
      inputSearchKey: event.detail.value
    });
    console.log(event.detail.value);
    
  },

  async search() {
    try {
      const db =  wx.cloud.database();
      const _ = wx.cloud.database().command;
      let key = this.data.inputSearchKey;
      console.log("查询的内容", key)
      let res = await db.collection('students').where(_.or([{
        name: db.RegExp({
          regexp: '.*' + key,
          options: 'i',
        })
      },
      {
        classify: db.RegExp({
          regexp: '.*' + key,
          options: 'i',
        })
      },
      {
        remark: db.RegExp({
          regexp: '.*' + key,
          options: 'i',
        })
      },
      {
        sex: db.RegExp({
          regexp: '.*' + key,
          options: 'i',
        })
      },
      ])).orderBy('_updateTime','desc').get()

      if (res.data.length === 0) {
        wx.showToast({
          title: '没有查询到结果',
          icon: 'none',
          duration:3000
        })
      } else {
        wx.showToast({
          title: '查询成功',
          icon: 'success'
        });
        this.setData({
          list: res.data 
        });
        // let takeExpressOrders = res.data as any;
        // takeExpressOrders.map((item)=> {
        //   let  receiverAddressString  = `${item.takeCode} ${item.name} ${item.phone} ${item.buildingName} ${item.dormitoryNumber}`
        //   item.receiverAddressString = receiverAddressString;
        // })
        // this.setData({
        //   takeExpressOrders:takeExpressOrders,
        // });
      }
    } catch (error) {
      console.log(error);
      wx.showToast({
        title: '查询出错',
        icon: 'none'
      })
    }
  },
  async getInitData(){
    let app = getApp();
    console.log(app.globalData.students);
    this.setData({
      list:app.globalData.students
    })
  },
  async delete(event:WechatMiniprogram.CustomEvent){
    console.log(event);
    let app = getApp();
    let index = event.currentTarget.dataset.index;
    app.globalData.students.splice(index,1)
    let students = app.globalData.students;
    console.log( students);
    wx.showLoading({title:'删除中',mask:true})
    let groupId = app.globalData.groupId;
    await wx.cloud.database().collection('groups').doc(groupId).update({data:{
      students:students
    }}).then(async res=>{
      wx.showToast({
        title:'删除成功'
      });
       await this.getInitData();
    })
  },

  async onShow() {
    await this.getInitData()
  },


  async getMoreData(){
    let currentPage = this.data.currentPage;
    currentPage+=1;
    let tips = "加载第" + (currentPage+1) + "页";
    console.log("load page " + (currentPage+1));
    wx.showLoading({title:tips});
    let list = await (await wx.cloud.database().collection('students').orderBy('_updateTime','desc').limit(20).skip(currentPage*20).get()).data;
    wx.hideLoading();
    // 将新一页的数据添加到原数据后面
    var originArticles = this.data.list;
    var newList = originArticles.concat(list);
    console.log(newList);
    this.setData({
      list: newList,
      currentPage: currentPage
    })
  },

  toAdd(){
    wx.navigateTo({url:'/pages/studentsAdd/studentsAdd'})
  },
  onPullDownRefresh() {
    console.log('目前刷新');
    this.setData({
      list:[],
      loadNumber:0,
    });
    this.getInitData()
  },
  onReachBottom() {
    console.log('已经到底了');
    // let currentPage = this.data.currentPage;
    // let loadNumberLimit = this.data.loadNumberLimit;
    // if(currentPage>=loadNumberLimit){
    //   wx.showToast({'title':'已经到底了',duration:3000})
    // }else{
    //   this.getMoreData()
    // }
  },

  onPageScroll(ev){
    var _this = this;
    if (ev.scrollTop <= 0) {
      ev.scrollTop = 0;
    } 
    if (ev.scrollTop > this.data.scrollTop || ev.scrollTop == wx.getSystemInfoSync().windowHeight) {
     this.setData({
       hidden:true
     })
    } else {
      this.setData({
        hidden:false
      })
    }
    setTimeout(function () {
      _this.setData({
        scrollTop: ev.scrollTop
      })
    }, 0)
  },

  toStudentEdit(){
    wx.navigateTo({url:'/pages/studentEdit/studentEdit'})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

 

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */


  /**
   * 页面上拉触底事件的处理函数
   */


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})